<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="名称" v-model="whereQuery.name">
      </el-input>
      <el-select clearable style="width: 90px" class="filter-item" v-model="whereQuery.type" placeholder="类型" @change="handleFilter">
        <el-option v-for="item in groupTypeOptions" :key="item" :label="item | groupTypeFilter" :value="item">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="updateAllStoreList" type="primary" icon="el-icon-edit">批量刷新</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%">
      <el-table-column align="center" label="id" width="300">
        <template slot-scope="scope">
          <span class="link-type" style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;" @click="showJsonObject(scope.row)">{{scope.row._id}}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" min-width="150px" label="名称" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" width="110px" label="说明" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.content}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="90px" label="类型">
        <template slot-scope="scope">
          <span>{{scope.row.type | groupTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="80px" label="查询条件">
        <template slot-scope="scope">
          <span v-if="scope.row.condition" class="link-type" @click="showConditionObject(scope.row.condition)">[query]</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="80px" label="头图">
        <template slot-scope="scope" v-if="scope.row.cover && scope.row.cover.url">
          <el-popover ref="coverPopover" placement="top" width="220" trigger="hover">
            <el-form>
              <el-form-item min-width="200">
                <img :src="scope.row.cover.url+'?imageView2/2/w/200/h/200'" class="avatar">
              </el-form-item>
            </el-form>
          </el-popover>
          <el-button v-popover:coverPopover type="text"  @click="openWindow(scope.row.cover.url)">cover</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" width="80px" label="更新周期">
        <template slot-scope="scope">
          <span>{{scope.row.period | periodTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column width="135px" align="center" label="首次更新时间">
        <template slot-scope="scope">
          <span v-if="scope.row.begin">{{scope.row.begin | momentFormat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="是否更新">
        <template slot-scope="scope">
          <span v-if="scope.row.update">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="更新成功">
        <template slot-scope="scope">
          <div v-if="scope.row.type === 2">
          <span v-if="scope.row.status">是</span>
          <span v-else>否</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="135px" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createdAt | momentFormat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230px" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.type === 2" type="success" size="mini" @click="updateListInfo(scope.row)">刷新</el-button>
          <el-button v-else type="success" size="mini" disabled>刷新</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="对象" :visible.sync="jsonVisible">
      <el-form label-position="right" style='min-width: 600px;'>
        <el-form-item>
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 27}" v-model="jsonObject">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 500px; margin-left:50px;'>
        <el-form-item label="列表名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="列表说明">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="temp.content">
          </el-input>
        </el-form-item>
        <el-form-item label="列表缩略图">
          <el-upload action="https://upload-z1.qbox.me" accept="image/*" :on-success = 'afterUpload' :data="dataObj" drag :multiple="false" :show-file-list="false" :before-upload="beforeUpload">
            <img v-if="coverUrl" :src="temp.cover.url+'?imageView2/2/w/200/h/200'" class="avatar">
            <div v-else>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </div>
          </el-upload>
          <div class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率 xx * xx)</div>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select class="filter-item" v-model="temp.type" placeholder="请选择" @change="handleShowType" v-bind:disabled="temp._id != undefined">
            <el-option v-for="item in groupTypeOptions" :key="item" :label="item | groupTypeFilter" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-show="showType2">
          <el-form-item label="查询条件">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 6}" placeholder="请输入查询条件" v-model="temp.condition">
            </el-input>
          </el-form-item>
          <el-form-item label="首次更新时间">
            <el-date-picker v-model="temp.begin" type="datetime" placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="更新周期">
            <el-select class="filter-item" v-model="temp.period" placeholder="请选择">
              <el-option v-for="item in periodOptions" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否需要更新">
            <el-select class="filter-item" v-model="temp.update" placeholder="请选择">
              <el-option v-for="item in booleanOptions" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { fetch, insert, update, cloud } from '@/api/jb'
  import { getToken } from '@/api/qiniu'
  import waves from '@/directive/waves' // 水波纹指令
  import { MessageBox } from 'element-ui'

  const periodOptions = [
    { key: 600, value: '10分钟' },
    { key: 3600, value: '1小时' },
    { key: 43200, value: '半天' },
    { key: 86400, value: '每天' }
  ]

  const booleanOptions = [
    { key: true, value: '是' },
    { key: false, value: '否' }
  ]

  export default {
    name: 'listGroup',
    directives: {
      waves
    },
    data() {
      return {
        list: null,
        total: null,
        listLoading: true,
        showType2: false,
        listQuery: {
          skip: 0,
          limit: 10,
          where: {
            name: {
              $regex: undefined
            },
            type: undefined
          },
          count: true,
          order: {

          }
        },
        whereQuery: {
          name: undefined,
          type: undefined
        },
        idParams: {
          id: undefined
        },
        groupTypeOptions: [1, 2],
        periodOptions,
        booleanOptions,
        sortOptions: [{ label: '按ID升序列', key: '+id' }, { label: '按ID降序', key: '-id' }],
        temp: {
          _id: undefined,
          name: undefined,
          type: 1,
          value: undefined,
          content: undefined,
          period: 0,
          begin: 0,
          update: false,
          condition: undefined,
          cover: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
        },
        dialogFormVisible: false,
        jsonVisible: false,
        jsonObject: undefined,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dataObj: { token: '', key: '' },
        coverUrl: undefined,
        qiniuParams: {
          fileName: 'listGroup',
          platform: 'qiniu'
        },
        rules: {
          name: [{ required: true, message: '列表名称不能为空', trigger: 'change' }],
          type: [{ required: true, message: '类型 is required', trigger: 'change' }]
        }
      }
    },
    filters: {
      groupTypeFilter(type) {
        const groupType = ['手动添加', '定时更新']
        return type > 0 ? groupType[ type - 1 ] : ''
      },
      periodTypeFilter(period) {
        var value
        for (const i in periodOptions) {
          if (periodOptions[i].key === period) {
            value = periodOptions[i].value
            break
          }
        }
        return value
      },
      json: (value) => { return JSON.stringify(value, null, 2) }
    },
    created() {
      this.getList()
    },
    methods: {
      beforeUpload() {
        const _self = this
        return new Promise((resolve, reject) => {
          getToken(this.qiniuParams).then(response => {
            const key = response.data.data.name
            const token = response.data.data.token
            _self._data.dataObj.token = token
            _self._data.dataObj.key = key
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        })
      },
      afterUpload(res) {
        this.temp.cover._id = res.data.file._id
        this.temp.cover.url = res.data.file.url
        this.coverUrl = res.data.file.url
      },
      updateAllStoreList() {
        cloud('updateAllStoreList', undefined).then(response => {
          if (response.data.code === 0) {
            this.$notify({
              title: '成功',
              message: '批量刷新成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message,
              type: 'info',
              duration: 2000
            })
          }
        })
      },
      getList() {
        this.listLoading = true
        if (this.whereQuery.name) {
          this.listQuery.where.name = {
            $regex: '.*' + this.whereQuery.name + '.*'
          }
        } else {
          this.listQuery.where.name = undefined
        }
        if (this.whereQuery.type) {
          this.listQuery.where.type = this.whereQuery.type
        } else {
          this.listQuery.where.type = undefined
        }
        fetch('ListGroup', this.listQuery).then(response => {
          this.list = response.data.data.result
          this.total = response.data.data.count
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.skip = 0
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.skip = (val - 1) * this.listQuery.limit
        this.getList()
      },
      handleShowType(type) {
        switch (type) {
          case 0 :
            break
          case 1:
            this.showType2 = false
            this.temp.condition = undefined
            this.temp.begin = undefined
            this.temp.period = undefined
            break
          case 2:
            this.showType2 = true
            break
          default:
        }
      },
      resetTemp() {
        this.temp = {
          _id: undefined,
          name: undefined,
          type: 1,
          value: undefined,
          content: undefined,
          period: undefined,
          begin: undefined,
          update: false,
          condition: undefined,
          cover: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
        }
      },
      handleCreate() {
        this.resetTemp()
        this.showType2 = false
        this.dataObj = {}
        this.coverUrl = undefined
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (this.temp.condition) {
              tempData.condition = JSON.stringify(JSON.parse(this.temp.condition))
            }
            if (this.temp.begin) {
              tempData.begin = new Date(this.temp.begin).getTime()
            }
            if (!this.temp.cover._id) {
              tempData.cover = undefined
            }
            insert('ListGroup', tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.listQuery.skip = 0
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        for (const key of Reflect.ownKeys(this.temp)) {
          this.temp[key] = row[key]
        }
        if (!this.temp.cover) {
          this.temp.cover = {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        if (this.temp.condition !== undefined) {
          this.temp.condition = JSON.stringify(JSON.parse(this.temp.condition), null, 4)
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        this.handleShowType(this.temp.type)
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (this.temp.condition) {
              tempData.condition = JSON.stringify(JSON.parse(this.temp.condition))
            }
            if (this.temp.begin) {
              tempData.begin = new Date(this.temp.begin).getTime()
            }
            if (!this.temp.cover || !this.temp.cover._id) {
              tempData.cover = undefined
            } else {
              this.coverUrl = this.temp.cover.url
            }
            update('ListGroup', this.temp._id, tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      updateListInfo(row) {
        this.idParams.id = row._id
        cloud('updateStoreList', this.idParams).then(response => {
          if (response.data.code === 0) {
            this.$notify({
              title: '成功',
              message: '刷新成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message,
              type: 'info',
              duration: 2000
            })
          }
        })
      },
      handleDelete(row) {
        MessageBox.confirm('是否确认删除？', '确定删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.idParams.id = row._id
          cloud('deleteListGroup', this.idParams).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        })
      },
      showJsonObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(data, null, 4)
      },
      showConditionObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(JSON.parse(data), null, 4)
      },
      openWindow(value) {
        window.open(value)
      }
    }
  }
</script>
<style scoped>

</style>
